"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SocketConnection = void 0;
const HallServer_SocketMsgHandler_1 = require("../../../../hall_server/HallServer_SocketMsgHandler");
const Config_1 = require("../../../config/Config");
const jhaoproto_1 = require("../../../lib/net/protobuf/jhaoproto");
const ProtoManager_1 = require("../../../lib/net/protobuf/ProtoManager");
const DateUtil_1 = require("../../utils/DateUtil");
const EventManager_1 = require("../../utils/EventManager");
const Logger_1 = require("../../utils/Logger");
const SocketClientMsgHandler_1 = require("./SocketClientMsgHandler");
const SocketConnectionManager_1 = require("./SocketConnectionManager");
const Check_Time_Inteval = 1000 * 5;
const NoMsg_Time_Inteval = 1000 * 30;
class SocketConnection {
    constructor(connection, ip) {
        this.id = 0;
        this.isDestroyed = false;
        this.gotoCloseTime = 0;
        this.connectTime = 0;
        this.timeCount = 0;
        this.lastRecvMsgTime = 0;
        this.isInternalServer = false;
        EventManager_1.EventManager.instance.on(Config_1.Config.Event_Config.Timer, this.onTimer, this);
        this.connection = connection;
        SocketConnection.id++;
        this.ip = ip;
        this.id = SocketConnection.id;
        this.connectTime = DateUtil_1.default.now();
        this.initConnect();
    }
    initConnect() {
        this.isDestroyed = false;
        this.isClosing = false;
        this.connection.on('close', () => {
            Logger_1.Logger.log('SocketConnection disconnected', this.account);
            this.destroy();
        });
        this.connection.on('message', (data) => {
            this.lastRecvMsgTime = DateUtil_1.default.now();
            this.onClientMsgHandler(data);
        });
    }
    onTimer(now) {
        if ((now - this.timeCount) >= Check_Time_Inteval) {
            this.timeCount = now;
            if (!this.isLogin()) { //连接后很久不登录释放连接 
                if (now - this.connectTime >= 1000 * 60) {
                    this.destroy();
                    return false;
                }
            }
            else {
                if (!this.isInternalServer && this.lastRecvMsgTime > 0 && (now - this.lastRecvMsgTime) >= NoMsg_Time_Inteval) {
                    this.lastRecvMsgTime = 0;
                    this.checkDestroyAccountConnect();
                }
            }
        }
        if (this.gotoCloseTime > 0 && now >= this.gotoCloseTime) {
            this.gotoCloseTime = 0;
            this.close(true);
        }
    }
    checkDestroyAccountConnect() {
        let isNeedDestroy = true;
        for (const key in Config_1.Config.ServerType_List) {
            let value = Config_1.Config.ServerType_List[key];
            if (this.account.includes(value)) {
                this.isInternalServer = true;
                isNeedDestroy = false;
                break;
            }
        }
        if (isNeedDestroy) {
            Logger_1.Logger.log("NoMsg_Time_Inteval=22=", this.account);
            this.destroy();
        }
    }
    checkConnection() {
        if (!this.connection) {
            this.destroy();
            return false;
        }
        else if (this.connection.readyState == SocketConnection.ReadyState.Close) {
            this.connection.terminate();
            this.destroy();
            return false;
        }
        return true;
    }
    gotoClose() {
        this.isClosing = true;
        this.gotoCloseTime = DateUtil_1.default.now() + 1000;
        // if(this.player){
        //     this.player.toDbStr() //数据回写
        // }
    }
    close(isForce = false) {
        if (this.connection.readyState == SocketConnection.ReadyState.Open || isForce) {
            this.connection.terminate();
            this.destroy();
        }
    }
    onClientMsgHandler(data) {
        try {
            // Logger.info("onClientMsgHandler======data==", data);
            let byteArray = new Uint8Array(data);
            let baseMsg = ProtoManager_1.ProtoManager.instance.decode(jhaoproto_1.JhaoProto.BaseMsg, byteArray);
            if (baseMsg.cmdIndex >= jhaoproto_1.JhaoProto.CmdIndex.server_internal_None) { //服务器内部信息
                SocketClientMsgHandler_1.SocketClientMsgHandler.onEventSocketGata(this, baseMsg);
            }
            else {
                if (baseMsg.cmdOrder > 0) {
                    HallServer_SocketMsgHandler_1.HallServer_SocketMsgHandler.onEventSocketGata(this, baseMsg);
                }
                else { //服务器内部消息
                    // SocketClientMsgHandler.onEventSocketGata(this, baseMsg);
                }
            }
        }
        catch (error) {
            Logger_1.Logger.info("onClientMsgHandler======error==", error);
            Logger_1.Logger.error("onClientMsgHandler======error==", error);
            this.close(true);
        }
    }
    createSendPack(baseMsg) {
        return ProtoManager_1.ProtoManager.instance.encode(jhaoproto_1.JhaoProto.BaseMsg, baseMsg);
    }
    //单纯把错误信息发送给客户端
    sendErrorToClient(cmdOrder, error_code, errorMsg, cmdIndex = jhaoproto_1.JhaoProto.CmdIndex.None) {
        let baseMsg = {
            cmdIndex: cmdIndex,
            cmdOrder: cmdOrder,
            timeDownload: DateUtil_1.default.now(),
            errorCode: error_code,
            errorMsg: errorMsg,
        };
        this.sendMsgToClient(baseMsg);
    }
    createMsgToClient(cmdIndex, cmdOrder, en_proto_ctor = null, data = null) {
        let baseMsg = {
            cmdOrder: cmdOrder,
            cmdIndex: cmdIndex,
            timeDownload: DateUtil_1.default.now(),
        };
        if (en_proto_ctor && data) {
            baseMsg.data = ProtoManager_1.ProtoManager.instance.encode(en_proto_ctor, data);
        }
        this.sendMsgToClient(baseMsg);
    }
    sendMsgToClient(socketMsg) {
        if (!this.checkConnection()) {
            return;
        }
        if (!this.isDestroyed) {
            this.connection.send(this.createSendPack(socketMsg));
        }
        else {
            Logger_1.Logger.error("sendMsgToClient=error=", this, socketMsg);
        }
    }
    isLogin() {
        if (this.account && this.account != null && this.account != "") {
            return true;
        }
        else {
            return false;
        }
    }
    destroy() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.isDestroyed) {
                EventManager_1.EventManager.instance.clear(this);
                Logger_1.Logger.log("socketconnection destroy=", this.account);
                this.isDestroyed = true;
                this.connection = null;
                this.account = null;
                if (this.user) {
                    this.user.destroy();
                }
                this.user = null;
                SocketConnectionManager_1.SocketConnectionManager.instance.removeSocketConnection(this);
            }
        });
    }
}
exports.SocketConnection = SocketConnection;
SocketConnection.ReadyState = {
    Open: 1,
    Close: 3
};
SocketConnection.id = 0;
